package com.ai.aicodemather.generator;

import cn.hutool.core.lang.Dict;
import cn.hutool.setting.yaml.YamlUtil;
import com.mybatisflex.codegen.Generator;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.util.HashMap;

/**
 * 自定义MybatisFlex 代码生成器
 */
public class MybatisFlexCodeGenerator {

    private static final String[] TABLE_NAME = {"app"};

    public static void main(String[] args) {
        Dict dict = YamlUtil.loadByPath("application.yml");
        HashMap<String, Object> datasource = dict.getByPath("spring.datasource");
        String url = datasource.get("url").toString();
        String name = datasource.get("username").toString();
        String password = datasource.get("password").toString();
        //配置数据源
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(url);
        dataSource.setUsername(name);
        dataSource.setPassword(password);

        //创建配置内容
        GlobalConfig globalConfig = createGlobalConfig();

        //通过 datasource 和 globalConfig 创建代码生成器
        Generator generator = new Generator(dataSource, globalConfig);

        //生成代码
        generator.generate();
    }

    public static GlobalConfig createGlobalConfig() {
        //创建配置内容
        GlobalConfig globalConfig = new GlobalConfig();

        //设置根包
        globalConfig.getPackageConfig()
                .setBasePackage("com.ai.aicodemather.gencode");

        //设置表前缀和只生成哪些表，setGenerateTable 未配置时，生成所有表
        globalConfig.getStrategyConfig()
                .setGenerateTable(TABLE_NAME);

        //设置生成 entity 并启用 Lombok
        globalConfig.enableEntity()
                .setWithLombok(true)
                .setJdkVersion(21);

        //设置生成 mapper
        globalConfig.enableMapper();
        globalConfig.enableMapperXml();
        //设置生成 service
        globalConfig.enableService();
        globalConfig.enableServiceImpl();
        //设置生成 controller
        globalConfig.enableController();
        //设置生成 xml
        globalConfig.getJavadocConfig()
                .setAuthor("aiCodeMather")
                .setSince("2023-03-30");

        return globalConfig;
    }
}